package com.saile.tool;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

public class HttpUtils {
    private static String[] IEBrowserSignals = {"MSIE", "Trident", "Edge"};

    public static boolean isMSBrowser(HttpServletRequest request) {
        String userAgent = request.getHeader("User-Agent");
        for (String signal : IEBrowserSignals) {
            if (userAgent.contains(signal))
                return true;
        }
        return false;
    }

    public static String encode(HttpServletRequest request,String fileName) throws UnsupportedEncodingException{
        boolean isMSIE = HttpUtils.isMSBrowser(request);
        String n = fileName;
        if (isMSIE) {
           n = URLEncoder.encode(fileName, "UTF-8");
        } else {
           n = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
        }
        return n;
    }
    public static void encode(HttpServletRequest request,HttpServletResponse response,String fileName) throws UnsupportedEncodingException{
        response.setContentType("application/octet-stream");
        String n = encode(request, fileName);
        response.setHeader("Content-disposition", "attachment;filename=\"" + n + "\"");
    }
}